const { ipcRenderer } = require('electron');
Vue.use(ELEMENT);
const userList = JSON.parse(localStorage.getItem('userList') || '[]');
const setting = JSON.parse(localStorage.getItem('setting') || JSON.stringify({
  protocol: 'http://',
  host: '49.232.15.194:1169/api/mind-server'
}));

const app = new Vue({
  el: '#app',
  data: {
    // 视图id
    viewId: null,
    // 用户名
    username: '',
    // 密码
    password: '',
    // 头像地址
    headImage: '',
    // 是否记住密码
    rember: false,
    // 自动登录
    autoLogin: false,
    // 登录历史账号
    userList,
    // 设置开关
    openSetting: false,
    // 设置项
    setting,
  },
  methods: {
    async login() {
      if (!this.username) {
        this.showMessage('error', '请输入用户名');
        return;
      }
      if (!this.password) {
        this.showMessage('error', '请输入密码');
        return;
      }
      this.showMessage();

      this.$refs.login.className = 'login el-icon-loading';
      const url = this.setting.protocol + this.setting.host;
      const result = await login(url, this.username, this.getPassword());
      this.$refs.login.className = 'login el-icon-right';

      const user = {
        username: this.username,
        password: '',
        rember: this.rember,
        autoLogin: this.autoLogin,
        time: Date.now(),
        md5: true,
      };
      if (!result.success) {
        this.showMessage('error', result.message);
        return;
      }
      this.showMessage('success', `你好，${ result.nickname }`);
      if (this.rember) {
        user.password = result.password;
      }
      user.headImage = result.headImage;
      this.pushUser(user);
      ipcRenderer.send('toExplor', {
        viewId: this.viewId,
        nickname: result.nickname,
        headImage: result.headImage
      });
    },
    showMessage(leval = '', message = '') {
      this.$refs.warn.innerText = message;
      switch (leval) {
        case 'error':
          this.$refs.warnIcon.className = 'el-icon-error';
          break;
        case 'success':
          this.$refs.warnIcon.className = 'el-icon-success';
          break;
        default:
          this.$refs.warnIcon.className = '';
          break;
      }
    },
    settingView(flag) {
      if (this.openSetting === flag) {
        return;
      }
      this.$refs.blur.style.left = '-200%';
      this.$refs.container.style.left = '100%';
      setTimeout(() => {
        this.$refs.blur.style.left = '-100%';
        this.$refs.container.style.left = '50%';
        this.openSetting = flag;
      }, 300);
    },
    getPassword() {
      for (const user of this.userList) {
        if (user.username === this.username) {
          return user.password === this.password ? { md5: this.password } : this.password;
        }
      }
      return this.password;
    },
    pushUser(newUser) {
      for (const user of this.userList) {
        if (user.username === newUser.username) {
          Object.assign(user, newUser);
          return;
        }
      }
      this.userList.push(newUser);
    },
    querySearchUser(keyword, callback) {
      callback(this.userList.filter(({ username }) => {
        return username.includes(keyword);
      }).map(({ username }) => {
        return { value: username };
      }));
    },
    selectUser({ value }) {
      for (const user of this.userList) {
        if (user.username === value) {
          Object.assign(this, user);
          break;
        }
      }
    },
    close() {
      ipcRenderer.send('close', this.viewId);
    }
  },
  watch: {
    userList: {
      deep: true,
      immediate: true,
      handler(data) {
        data = JSON.parse(JSON.stringify(data));
          data = data.sort((a, b) => {
            return a.time > b.time ? -1 : 1;
          });
        localStorage.setItem('userList', JSON.stringify(data));
      }
    },
    setting: {
      deep: true,
      immediate: true,
      handler(data) {
        localStorage.setItem('setting', JSON.stringify(data));
      }
    },
    autoLogin(flag) {
      if (flag) {
        this.rember = true;
      }
    }
  }
});

ipcRenderer.on('viewId', (_event, viewId) => {
  app.viewId = viewId;
});

if (userList.length > 0) {
  Object.assign(app, userList[0]);
  if (app.autoLogin) {
    app.showMessage('', '自动登陆中...');
    setTimeout(() => {
      app.login();
    }, 500);
  }
}

function login(url, username, password) {
  ipcRenderer.send('login', { url, username, password });
  return Promise.race([
    new Promise((resolve) => {
      ipcRenderer.once('loginResult', (_event, result) => {
        resolve(result);
      });
    }),
    new Promise((resolve) => {
      setTimeout(() =>{
        resolve({ success: false, message: '请求超时!' });
      }, 3000);
    }),
  ]);
}
